package com.university.evaluation.service;

import com.university.evaluation.entity.AuditFlow;
import com.university.evaluation.entity.ScoreRecord;
import com.university.evaluation.mapper.AuditFlowMapper;
import com.university.evaluation.mapper.ScoreRecordMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 材料审核状态流转服务
 * 状态流转规则：PENDING_MON（待班委审核）-> PENDING_TCH（待辅导员审核）-> FINISHED（完成）
 * 拒绝时状态直接设为REJECT，支持学生补充材料后重新提交（状态回退至PENDING_MON）
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MaterialAuditService {

    private final ScoreRecordMapper scoreRecordMapper;
    private final AuditFlowMapper auditFlowMapper;
    private final NoticeService noticeService;

    /**
     * 班委初审材料
     * @param materialId 材料ID
     * @param auditResult 审核结果（PASS/REJECT）
     * @param opinion 审核意见
     * @param auditorId 审核人ID（班委）
     * @return 审核结果
     */
    @Transactional
    public AuditResult monitorAudit(String materialId, String auditResult, String opinion, String auditorId) {
        log.info("班委初审材料：materialId={}, auditResult={}, auditorId={}", materialId, auditResult, auditorId);
        
        // 1. 查询材料当前状态（仅允许PENDING_MON状态进行初审）
        ScoreRecord record = scoreRecordMapper.selectById(materialId);
        if (record == null) {
            return new AuditResult(false, "材料记录不存在");
        }
        
        if (!ScoreRecord.STATUS_PENDING_MON.equals(record.getStatus())) {
            return new AuditResult(false, "材料当前状态不允许初审，当前状态：" + record.getStatus());
        }

        // 2. 更新材料状态
        ScoreRecord updateRecord = new ScoreRecord();
        updateRecord.setRecordId(materialId);
        updateRecord.setUpdateTime(LocalDateTime.now());
        
        if (AuditFlow.AUDIT_STATUS_PASS.equals(auditResult)) {
            updateRecord.setStatus(ScoreRecord.STATUS_PENDING_TCH); // 初审通过，流转至辅导员审核
        } else {
            updateRecord.setStatus(ScoreRecord.STATUS_REJECT); // 初审拒绝，状态设为拒绝
        }
        scoreRecordMapper.updateById(updateRecord);

        // 3. 记录审核日志
        AuditFlow auditFlow = new AuditFlow();
        auditFlow.setAuditId(UUID.randomUUID().toString());
        auditFlow.setRecordId(materialId);
        auditFlow.setAuditorId(auditorId);
        auditFlow.setAuditOpinion(opinion);
        auditFlow.setAuditStatus(auditResult);
        auditFlow.setAuditTime(LocalDateTime.now());
        auditFlowMapper.insert(auditFlow);

        // 4. 发送通知（初审通过通知辅导员，拒绝通知学生）
        if (AuditFlow.AUDIT_STATUS_PASS.equals(auditResult)) {
            noticeService.sendNotice(findTeacherByCollege(record.getUserId()), 
                "待审核提醒", "有新的班级材料需终审", "SYSTEM_MSG");
        } else {
            noticeService.sendNotice(record.getUserId(), 
                "审核结果通知", "材料初审拒绝：" + opinion, "SYSTEM_MSG");
        }

        log.info("班委初审完成：materialId={}, 新状态={}", materialId, updateRecord.getStatus());
        return new AuditResult(true, "初审完成");
    }

    /**
     * 辅导员终审材料
     * @param materialId 材料ID
     * @param auditResult 审核结果（PASS/REJECT）
     * @param opinion 审核意见
     * @param auditorId 审核人ID（辅导员）
     * @param finalScore 最终得分（通过时必填）
     * @return 审核结果
     */
    @Transactional
    public AuditResult teacherAudit(String materialId, String auditResult, String opinion, 
                                   String auditorId, Double finalScore) {
        log.info("辅导员终审材料：materialId={}, auditResult={}, auditorId={}", materialId, auditResult, auditorId);
        
        // 1. 查询材料当前状态（仅允许PENDING_TCH状态进行终审）
        ScoreRecord record = scoreRecordMapper.selectById(materialId);
        if (record == null) {
            return new AuditResult(false, "材料记录不存在");
        }
        
        if (!ScoreRecord.STATUS_PENDING_TCH.equals(record.getStatus())) {
            return new AuditResult(false, "材料当前状态不允许终审，当前状态：" + record.getStatus());
        }

        // 2. 更新材料状态和得分
        ScoreRecord updateRecord = new ScoreRecord();
        updateRecord.setRecordId(materialId);
        updateRecord.setUpdateTime(LocalDateTime.now());
        
        if (AuditFlow.AUDIT_STATUS_PASS.equals(auditResult)) {
            updateRecord.setStatus(ScoreRecord.STATUS_PASS); // 终审通过
            if (finalScore != null) {
                updateRecord.setScore(java.math.BigDecimal.valueOf(finalScore));
            }
        } else {
            updateRecord.setStatus(ScoreRecord.STATUS_REJECT); // 终审拒绝
        }
        scoreRecordMapper.updateById(updateRecord);

        // 3. 记录审核日志
        AuditFlow auditFlow = new AuditFlow();
        auditFlow.setAuditId(UUID.randomUUID().toString());
        auditFlow.setRecordId(materialId);
        auditFlow.setAuditorId(auditorId);
        auditFlow.setAuditOpinion(opinion);
        auditFlow.setAuditStatus(auditResult);
        auditFlow.setAuditTime(LocalDateTime.now());
        auditFlowMapper.insert(auditFlow);

        // 4. 发送通知给学生
        String noticeContent = AuditFlow.AUDIT_STATUS_PASS.equals(auditResult) 
            ? "材料审核通过，得分：" + finalScore 
            : "材料审核拒绝：" + opinion;
        noticeService.sendNotice(record.getUserId(), "审核结果通知", noticeContent, "SYSTEM_MSG");

        log.info("辅导员终审完成：materialId={}, 新状态={}", materialId, updateRecord.getStatus());
        return new AuditResult(true, "终审完成");
    }

    /**
     * 根据学生所属学院查找辅导员
     */
    private String findTeacherByCollege(String studentId) {
        // TODO: 实现根据学生查找对应辅导员的逻辑
        return "TCH001"; // 临时返回
    }

    /**
     * 审核结果类
     */
    public static class AuditResult {
        private boolean success;
        private String message;

        public AuditResult(boolean success, String message) {
            this.success = success;
            this.message = message;
        }

        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
    }
}
